#!/bin/bash

###########################################################
#                勾股系统自动化安装脚本                     #
# 功能:                                                  #
# 1. 可选择安装勾股OA、勾股博客、勾股开发系统               #
# 2. 每个系统可自定义HTTP/HTTPS端口(带默认值)              #
# 3. 自动安装Nginx、PHP 8.3、MySQL 8.0                   #
# 4. 根据是否提供域名自动配置HTTP/HTTPS访问方式            #
# 5. 仅支持CentOS系统                                    #
# 6. 自动关闭SELinux以简化配置                            #
# 7. 支持卸载勾股OA、博客、开发系统                        #
# 8. 检测并处理已存在的Nginx、PHP、MySQL服务               #
# 9. 必须升级系统到CentOS 7.9才能继续安装                  #
# 版本: 4.8                                              #
###########################################################

# 检查是否为 root 用户
if [ "$(id -u)" -ne 0 ]; then
    echo "请使用 sudo 或以 root 用户运行此脚本！" >&2
    exit 1
fi

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
NC='\033[0m'

# 获取本机IP地址
get_local_ip() {
    ip -o -4 addr show | awk '{print $4}' | cut -d'/' -f1 | grep -v '127.0.0.1' | head -n1
}

# 检查系统版本和兼容性
check_system_compatibility() {
    echo -e "${GREEN}=== 检查系统兼容性 ===${NC}"
    
    # 检查系统是否为CentOS
    if [ ! -f /etc/redhat-release ]; then
        echo -e "${RED}错误：此脚本仅支持 CentOS 系统！${NC}"
        exit 1
    fi

    # 提取CentOS版本号
    OS_VERSION=$(grep -oE '[0-9]+\.[0-9]+' /etc/redhat-release | cut -d. -f1)
    OS_MINOR_VERSION=$(grep -oE '[0-9]+\.[0-9]+' /etc/redhat-release | cut -d. -f2)
    echo -e "${GREEN}检测到系统版本: CentOS $OS_VERSION.$OS_MINOR_VERSION${NC}"

    if [ "$OS_VERSION" != "7" ]; then
        echo -e "${YELLOW}警告：此脚本主要针对 CentOS 7 优化，当前版本为 CentOS $OS_VERSION${NC}"
        read -p "是否继续？(y/N): " CONTINUE_INSTALL
        if [[ ! $CONTINUE_INSTALL =~ ^[Yy]$ ]]; then
            exit 1
        fi
    fi
}

# 配置CentOS镜像源
configure_centos_repo() {
    echo -e "${GREEN}=== 配置 CentOS 镜像源 ===${NC}"
    
    # 首先测试当前镜像源是否可用
    echo -e "${YELLOW}测试当前镜像源可用性...${NC}"
    if yum makecache > /dev/null 2>&1; then
        echo -e "${GREEN}当前镜像源可用，无需更换${NC}"
        return 0
    fi
    
    echo -e "${YELLOW}当前镜像源不可用，开始配置国内镜像源...${NC}"
    
    # 备份原有配置
    echo -e "${GREEN}备份原有 yum 配置...${NC}"
    BACKUP_DIR="/etc/yum.repos.d/backup_$(date +%Y%m%d_%H%M%S)"
    mkdir -p "$BACKUP_DIR"
    cp /etc/yum.repos.d/CentOS-*.repo "$BACKUP_DIR/" 2>/dev/null || true

# 创建综合配置
cat > /etc/yum.repos.d/centos-all-mirrors.repo << 'EOF'
[base]
name=CentOS-7 - Base
failovermethod=priority
baseurl=https://mirrors.tuna.tsinghua.edu.cn/centos/7/os/x86_64/
        https://mirrors.huaweicloud.com/centos/7/os/x86_64/
        https://mirrors.aliyun.com/centos/7/os/x86_64/
        https://mirrors.bfsu.edu.cn/centos/7/os/x86_64/
        https://mirrors.shu.edu.cn/centos/7/os/x86_64/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
enabled=1

[base-vault]
name=CentOS-7 - Base Vault
baseurl=https://mirrors.tuna.tsinghua.edu.cn/centos-vault/7.$releasever/os/x86_64/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
enabled=0

[updates]
name=CentOS-7 - Updates
failovermethod=priority
baseurl=https://mirrors.tuna.tsinghua.edu.cn/centos/7/updates/x86_64/
        https://mirrors.huaweicloud.com/centos/7/updates/x86_64/
        https://mirrors.aliyun.com/centos/7/updates/x86_64/
        https://mirrors.bfsu.edu.cn/centos/7/updates/x86_64/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
enabled=1

[updates-vault]
name=CentOS-7 - Updates Vault
baseurl=https://mirrors.tuna.tsinghua.edu.cn/centos-vault/7.$releasever/updates/x86_64/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
enabled=0

[extras]
name=CentOS-7 - Extras
failovermethod=priority
baseurl=https://mirrors.tuna.tsinghua.edu.cn/centos/7/extras/x86_64/
        https://mirrors.huaweicloud.com/centos/7/extras/x86_64/
        https://mirrors.aliyun.com/centos/7/extras/x86_64/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
enabled=1

[centosplus]
name=CentOS-7 - Plus
failovermethod=priority
baseurl=https://mirrors.tuna.tsinghua.edu.cn/centos/7/centosplus/x86_64/
        https://mirrors.huaweicloud.com/centos/7/centosplus/x86_64/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
enabled=0

[epel]
name=EPEL 7
failovermethod=priority
baseurl=https://mirrors.tuna.tsinghua.edu.cn/epel/7/x86_64/
        https://mirrors.huaweicloud.com/epel/7/x86_64/
        https://mirrors.aliyun.com/epel/7/x86_64/
gpgcheck=1
gpgkey=https://mirrors.tuna.tsinghua.edu.cn/epel/RPM-GPG-KEY-EPEL-7
enabled=1
EOF

    # 禁用原有的 CentOS 源（重命名而不是删除）
    for repo in /etc/yum.repos.d/CentOS-*.repo; do
        if [ -f "$repo" ] && [ "$repo" != "/etc/yum.repos.d/centos-all-mirrors.repo" ]; then
            mv "$repo" "$repo.bak"
        fi
    done

    echo -e "${GREEN}清理 yum 缓存...${NC}"
    yum clean all

    echo -e "${GREEN}更新缓存...${NC}"
    if ! yum makecache; then
        echo -e "${YELLOW}警告：缓存更新遇到问题，尝试使用单个镜像源...${NC}"
        # 如果多镜像源失败，尝试使用单个镜像源
        sed -i 's|^baseurl=.*|baseurl=https://mirrors.tuna.tsinghua.edu.cn/centos/7/os/x86_64/|' /etc/yum.repos.d/centos-all-mirrors.repo
        sed -i '/baseurl=.*/d' /etc/yum.repos.d/centos-all-mirrors.repo
        sed -i '/\[updates\]/,/\[.*\]/ s|^baseurl=.*|baseurl=https://mirrors.tuna.tsinghua.edu.cn/centos/7/updates/x86_64/|' /etc/yum.repos.d/centos-all-mirrors.repo
        sed -i '/\[extras\]/,/\[.*\]/ s|^baseurl=.*|baseurl=https://mirrors.tuna.tsinghua.edu.cn/centos/7/extras/x86_64/|' /etc/yum.repos.d/centos-all-mirrors.repo
        yum clean all
        yum makecache
    fi

    echo -e "${GREEN}查看配置的仓库列表：${NC}"
    yum repolist

    echo -e "${GREEN}测试仓库可用性...${NC}"
    if yum --disablerepo="*" --enablerepo="base" list available > /dev/null 2>&1; then
        echo -e "${GREEN}✅ 镜像源配置成功！${NC}"
    else
        echo -e "${RED}❌ 镜像源配置可能有问题，请检查网络连接${NC}"
        echo -e "${YELLOW}如需恢复原配置，请运行: cp $BACKUP_DIR/*.repo /etc/yum.repos.d/${NC}"
        return 1
    fi

    echo -e "${GREEN}==========================================${NC}"
    echo -e "${GREEN}CentOS 镜像源配置完成！${NC}"
    echo -e "${GREEN}系统版本: CentOS $OS_VERSION${NC}"
    echo -e "${GREEN}备份位置: $BACKUP_DIR${NC}"
}

# 询问用户是否升级系统
ask_system_upgrade() {
    echo -e "${GREEN}=== 系统升级确认 ===${NC}"
    
    # 检查当前版本
    CURRENT_VERSION=$(grep -oE '[0-9]+\.[0-9]+' /etc/redhat-release)
    echo -e "${YELLOW}当前系统版本: CentOS $CURRENT_VERSION${NC}"
    
    if [ "$CURRENT_VERSION" == "7.9" ]; then
        echo -e "${GREEN}系统已经是 CentOS 7.9，无需升级${NC}"
        return 0
    fi
    
    echo -e "${YELLOW}检测到您的系统不是 CentOS 7.9 最新版本${NC}"
    echo -e "${YELLOW}系统升级可以确保软件兼容性和安全性${NC}"
    echo -e "${YELLOW}升级过程可能需要较长时间，且需要稳定的网络连接${NC}"
    echo -e "${RED}注意：必须升级系统到 CentOS 7.9 才能继续安装勾股系统！${NC}"
    
    while true; do
        read -p "是否要升级系统到 CentOS 7.9？(Y/n): " UPGRADE_CHOICE
        
        case ${UPGRADE_CHOICE:-Y} in
            [Yy]*)
                echo -e "${GREEN}用户确认系统升级，将先配置镜像源然后执行升级...${NC}"
                
                # 先配置镜像源
                configure_centos_repo
                
                # 然后执行升级
                upgrade_centos_system
                break
                ;;
            [Nn]*)
                echo -e "${RED}系统升级被用户取消，退出安装脚本${NC}"
                echo -e "${YELLOW}请在系统升级到 CentOS 7.9 后重新运行此脚本${NC}"
                exit 1
                ;;
            *)
                echo -e "${RED}无效选择，请输入 Y 或 N${NC}"
                ;;
        esac
    done
}

# 升级系统到CentOS 7.9
upgrade_centos_system() {
    echo -e "${GREEN}=== 开始升级系统到 CentOS 7.9 ===${NC}"
    
    # 检查当前版本
    CURRENT_VERSION=$(grep -oE '[0-9]+\.[0-9]+' /etc/redhat-release)
    echo -e "${YELLOW}当前系统版本: CentOS $CURRENT_VERSION${NC}"
    echo -e "${YELLOW}开始升级系统到 CentOS 7.9...${NC}"
    echo -e "${YELLOW}这个过程可能需要较长时间，请耐心等待...${NC}"
    echo -e "${YELLOW}升级过程中请不要中断操作...${NC}"
    
    # 执行系统升级
    if yum update -y; then
        echo -e "${GREEN}系统升级完成！${NC}"
        
        # 检查升级后的版本
        NEW_VERSION=$(grep -oE '[0-9]+\.[0-9]+' /etc/redhat-release)
        echo -e "${GREEN}升级后系统版本: CentOS $NEW_VERSION${NC}"
        
        if [ "$NEW_VERSION" != "7.9" ]; then
            echo -e "${YELLOW}系统已升级但不是 7.9 版本，当前版本: $NEW_VERSION${NC}"
            echo -e "${YELLOW}这可能是由于仓库中可用的最新版本不同${NC}"
        else
            echo -e "${GREEN}✅ 系统已成功升级到 CentOS 7.9${NC}"
        fi
        
        # 必须重启系统
        echo -e "${RED}系统升级完成，必须重启系统以确保所有更新生效！${NC}"
        echo -e "${YELLOW}系统将在 10 秒后自动重启...${NC}"
        echo -e "${GREEN}重启后请重新运行此脚本继续安装${NC}"
        
        # 倒计时
        for i in {10..1}; do
            echo -e "${YELLOW}${i}秒后重启...${NC}"
            sleep 1
        done
        
        echo -e "${GREEN}系统即将重启...${NC}"
        reboot
        exit 0
        
    else
        echo -e "${RED}系统升级失败！${NC}"
        echo -e "${YELLOW}继续安装可能会遇到兼容性问题${NC}"
        read -p "是否继续安装？(y/N): " CONTINUE_AFTER_FAIL
        if [[ ! $CONTINUE_AFTER_FAIL =~ ^[Yy]$ ]]; then
            exit 1
        fi
    fi
}

# 检测已存在的服务
detect_existing_services() {
    echo -e "${GREEN}=== 检测已存在的服务 ===${NC}"
    
    # 检测Nginx
    if command -v nginx >/dev/null 2>&1; then
        echo -e "${YELLOW}检测到已安装的 Nginx${NC}"
        EXISTING_NGINX=true
        NGINX_VERSION=$(nginx -v 2>&1 | cut -d'/' -f2)
        echo -e "${GREEN}Nginx 版本: $NGINX_VERSION${NC}"
    else
        EXISTING_NGINX=false
        echo -e "${GREEN}未检测到 Nginx${NC}"
    fi
    
    # 检测PHP
    if command -v php >/dev/null 2>&1; then
        echo -e "${YELLOW}检测到已安装的 PHP${NC}"
        EXISTING_PHP=true
        PHP_VERSION=$(php -v 2>/dev/null | head -1 | cut -d' ' -f2)
        echo -e "${GREEN}PHP 版本: $PHP_VERSION${NC}"
        
        # 检测PHP-FPM
        if systemctl is-active --quiet php-fpm 2>/dev/null || systemctl is-active --quiet php83-php-fpm 2>/dev/null; then
            EXISTING_PHP_FPM=true
            echo -e "${GREEN}检测到运行的 PHP-FPM 服务${NC}"
        else
            EXISTING_PHP_FPM=false
        fi
    else
        EXISTING_PHP=false
        EXISTING_PHP_FPM=false
        echo -e "${GREEN}未检测到 PHP${NC}"
    fi
    
    # 检测MySQL
    if command -v mysql >/dev/null 2>&1; then
        echo -e "${YELLOW}检测到已安装的 MySQL${NC}"
        EXISTING_MYSQL=true
        if systemctl is-active --quiet mysqld 2>/dev/null; then
            EXISTING_MYSQL_RUNNING=true
            echo -e "${GREEN}MySQL 服务正在运行${NC}"
        else
            EXISTING_MYSQL_RUNNING=false
            echo -e "${YELLOW}MySQL 服务未运行${NC}"
        fi
    else
        EXISTING_MYSQL=false
        EXISTING_MYSQL_RUNNING=false
        echo -e "${GREEN}未检测到 MySQL${NC}"
    fi
    
    # 显示检测结果
    echo -e "${GREEN}=== 服务检测完成 ===${NC}"
}

# 处理已存在的服务
handle_existing_services() {
    echo -e "${GREEN}=== 处理已存在的服务 ===${NC}"
    
    # 处理Nginx
    if [ "$EXISTING_NGINX" = true ]; then
        echo -e "${YELLOW}检测到已存在的 Nginx 服务${NC}"
        echo "请选择处理方式:"
        echo "1. 使用现有 Nginx 服务（推荐）"
        echo "2. 停止现有 Nginx 服务并重新安装"
        echo "3. 卸载现有 Nginx 服务并重新安装"
        read -p "请选择 (1-3，默认1): " NGINX_HANDLE
        
        case ${NGINX_HANDLE:-1} in
            1)
                echo -e "${GREEN}使用现有 Nginx 服务${NC}"
                SKIP_NGINX_INSTALL=true
                ;;
            2)
                echo -e "${YELLOW}停止现有 Nginx 服务${NC}"
                systemctl stop nginx
                SKIP_NGINX_INSTALL=false
                ;;
            3)
                echo -e "${RED}卸载现有 Nginx 服务${NC}"
                yum remove -y nginx
                SKIP_NGINX_INSTALL=false
                ;;
            *)
                echo -e "${GREEN}使用现有 Nginx 服务${NC}"
                SKIP_NGINX_INSTALL=true
                ;;
        esac
    else
        SKIP_NGINX_INSTALL=false
    fi
    
    # 处理PHP
    if [ "$EXISTING_PHP" = true ]; then
        echo -e "${YELLOW}检测到已存在的 PHP 环境${NC}"
        echo "请选择处理方式:"
        echo "1. 使用现有 PHP 环境"
        echo "2. 安装 PHP 8.3（可能覆盖现有配置）"
        echo "3. 保留现有 PHP 并安装 PHP 8.3（多版本共存）"
        read -p "请选择 (1-3，默认1): " PHP_HANDLE
        
        case ${PHP_HANDLE:-1} in
            1)
                echo -e "${GREEN}使用现有 PHP 环境${NC}"
                SKIP_PHP_INSTALL=true
                # 确定PHP-FPM服务名
                if systemctl is-active --quiet php83-php-fpm 2>/dev/null; then
                    PHP_FPM_SERVICE="php83-php-fpm"
                else
                    PHP_FPM_SERVICE="php-fpm"
                fi
                ;;
            2)
                echo -e "${YELLOW}安装 PHP 8.3（可能覆盖现有配置）${NC}"
                SKIP_PHP_INSTALL=false
                ;;
            3)
                echo -e "${YELLOW}保留现有 PHP 并安装 PHP 8.3${NC}"
                SKIP_PHP_INSTALL=false
                # 这里保持多版本共存，安装时会处理
                ;;
            *)
                echo -e "${GREEN}使用现有 PHP 环境${NC}"
                SKIP_PHP_INSTALL=true
                ;;
        esac
    else
        SKIP_PHP_INSTALL=false
    fi
    
    # 处理MySQL
    if [ "$EXISTING_MYSQL" = true ]; then
        echo -e "${YELLOW}检测到已存在的 MySQL 服务${NC}"
        echo "请选择处理方式:"
        echo "1. 使用现有 MySQL 服务（需要提供root密码）"
        echo "2. 安装新的 MySQL 8.0（多实例）"
        echo "3. 重新安装 MySQL 8.0（会删除现有数据）"
        read -p "请选择 (1-3，默认1): " MYSQL_HANDLE
        
        case ${MYSQL_HANDLE:-1} in
            1)
                echo -e "${GREEN}使用现有 MySQL 服务${NC}"
                SKIP_MYSQL_INSTALL=true
                # 验证MySQL连接
                if [ "$EXISTING_MYSQL_RUNNING" = true ]; then
                    echo -e "${YELLOW}请提供现有 MySQL 的 root 密码进行验证${NC}"
                    read -s -p "MySQL root 密码: " EXISTING_MYSQL_PASSWORD
                    echo
                    
                    if mysql -u root -p"$EXISTING_MYSQL_PASSWORD" -e "SELECT 1;" 2>/dev/null; then
                        echo -e "${GREEN}MySQL 连接验证成功${NC}"
                        MYSQL_PASSWORD="$EXISTING_MYSQL_PASSWORD"
                    else
                        echo -e "${RED}MySQL 连接验证失败${NC}"
                        echo -e "${YELLOW}将改为安装新的 MySQL 实例${NC}"
                        SKIP_MYSQL_INSTALL=false
                    fi
                else
                    echo -e "${YELLOW}MySQL 服务未运行，尝试启动...${NC}"
                    systemctl start mysqld
                    sleep 5
                fi
                ;;
            2)
                echo -e "${YELLOW}安装新的 MySQL 8.0 实例${NC}"
                SKIP_MYSQL_INSTALL=false
                # 这里需要处理多实例配置，但为了简化，我们使用默认实例
                ;;
            3)
                echo -e "${RED}重新安装 MySQL 8.0（会删除现有数据）${NC}"
                read -p "确定要删除现有 MySQL 数据吗？(y/N): " CONFIRM_REINSTALL
                if [[ $CONFIRM_REINSTALL =~ ^[Yy]$ ]]; then
                    systemctl stop mysqld
                    yum remove -y mysql-community-server mysql-community-client
                    rm -rf /var/lib/mysql
                    rm -rf /var/log/mysqld.log
                    SKIP_MYSQL_INSTALL=false
                else
                    echo -e "${GREEN}取消重新安装，使用现有 MySQL${NC}"
                    SKIP_MYSQL_INSTALL=true
                fi
                ;;
            *)
                echo -e "${GREEN}使用现有 MySQL 服务${NC}"
                SKIP_MYSQL_INSTALL=true
                ;;
        esac
    else
        SKIP_MYSQL_INSTALL=false
    fi
}

# 显示主菜单
show_main_menu() {
    echo -e "${GREEN}=== 勾股系统管理脚本 ===${NC}"
    echo "1. 安装勾股系统"
    echo "2. 卸载勾股系统"
    echo "3. 退出"
    read -p "请选择操作 (1-3): " MAIN_CHOICE
}

# 显示欢迎信息
show_welcome() {
    echo -e "${GREEN}=== 勾股系统安装脚本 (CentOS专用) ===${NC}"
}

# 安装基础软件
install_base_software() {
    echo -e "${GREEN}=== 安装基础软件 ===${NC}"
    
    if [ "$OS_VERSION" == "7" ]; then
        echo -e "${GREEN}=== CentOS 7 配置 ===${NC}"
        
        # 安装EPEL
        if ! yum list installed epel-release >/dev/null 2>&1; then
            echo -e "${YELLOW}安装EPEL仓库...${NC}"
            yum install -y epel-release
        fi
        
        # 安装Remi仓库
        if ! yum list installed remi-release >/dev/null 2>&1; then
            echo -e "${YELLOW}安装Remi仓库...${NC}"
            yum install -y https://rpms.remirepo.net/enterprise/remi-release-7.rpm
        fi
        
        # 安装 MySQL 8.0 仓库（如果不需要安装MySQL则跳过）
        if [ "$SKIP_MYSQL_INSTALL" = false ]; then
            if ! yum list installed mysql80-community-release >/dev/null 2>&1; then
                echo -e "${YELLOW}配置MySQL仓库...${NC}"
                rpm -Uvh https://dev.mysql.com/get/mysql80-community-release-el7-11.noarch.rpm
            fi
        fi
        
        yum install -y yum-utils curl wget git unzip
    else
        yum install -y curl wget git unzip
    fi
}

# 关闭 SELinux
disable_selinux() {
    echo -e "${GREEN}=== 关闭 SELinux ===${NC}"
    
    if command -v getenforce &>/dev/null; then
        SELINUX_STATUS=$(getenforce)
        if [ "$SELINUX_STATUS" == "Enforcing" ]; then
            echo -e "${YELLOW}正在禁用 SELinux...${NC}"
            
            # 临时设置为宽松模式（立即生效）
            setenforce 0
            
            # 永久禁用 SELinux
            sed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/selinux/config
            
            echo -e "${GREEN}SELinux 已禁用${NC}"
            echo -e "${YELLOW}注意：系统需要重启才能使永久禁用生效${NC}"
        else
            echo -e "${GREEN}SELinux 已经是宽松模式或已禁用${NC}"
        fi
    else
        echo -e "${YELLOW}未找到 SELinux，跳过配置${NC}"
    fi
}

# 安装Nginx
install_nginx() {
    if [ "$SKIP_NGINX_INSTALL" = true ]; then
        echo -e "${GREEN}跳过 Nginx 安装，使用现有服务${NC}"
        return 0
    fi
    
    echo -e "${GREEN}=== 安装Nginx ===${NC}"
    yum install -y nginx
    systemctl enable nginx
    systemctl start nginx
}

# 安装PHP
install_php() {
    if [ "$SKIP_PHP_INSTALL" = true ]; then
        echo -e "${GREEN}跳过 PHP 安装，使用现有服务${NC}"
        
        # 确保PHP-FPM服务运行
        if systemctl is-active --quiet "$PHP_FPM_SERVICE"; then
            echo -e "${GREEN}PHP-FPM 服务正在运行${NC}"
        else
            echo -e "${YELLOW}启动 PHP-FPM 服务...${NC}"
            systemctl start "$PHP_FPM_SERVICE"
        fi
        return 0
    fi
    
    echo -e "${GREEN}=== 安装PHP及相关扩展 ===${NC}"
    
    if [ "$OS_VERSION" == "7" ]; then
        # 尝试安装PHP 8.3
        echo -e "${YELLOW}尝试安装PHP 8.3...${NC}"
        if yum install -y php83 php83-php-fpm php83-php-xml php83-php-cli \
                          php83-php-mysqlnd php83-php-pdo php83-php-mbstring php83-php-curl \
                          php83-php-fileinfo php83-php-gd php83-php-zip php83-php-opcache 2>/dev/null; then
            echo -e "${GREEN}PHP 8.3 安装成功${NC}"
            # 创建符号链接
            ln -sf /opt/remi/php83/root/usr/bin/php /usr/bin/php
            ln -sf /opt/remi/php83/root/usr/sbin/php-fpm /usr/sbin/php-fpm
            PHP_FPM_SERVICE="php83-php-fpm"
            PHP_FPM_CONF="/etc/opt/remi/php83/php-fpm.d/www.conf"
        else
            # 回退到系统自带PHP
            echo -e "${YELLOW}PHP 8.3安装失败，安装系统自带PHP...${NC}"
            yum install -y php php-fpm php-xml php-cli \
                          php-mysqlnd php-pdo php-mbstring php-curl \
                          php-fileinfo php-gd php-zip php-opcache
            PHP_FPM_SERVICE="php-fpm"
            PHP_FPM_CONF="/etc/php-fpm.d/www.conf"
        fi
        
        # 配置 PHP-FPM
        if [ -f "$PHP_FPM_CONF" ]; then
            # 确保 PHP-FPM 监听 TCP
            sed -i 's/^listen = .*/listen = 127.0.0.1:9000/' "$PHP_FPM_CONF"
            # 修改用户组
            sed -i 's/^user = .*/user = nginx/' "$PHP_FPM_CONF"
            sed -i 's/^group = .*/group = nginx/' "$PHP_FPM_CONF"
        fi
    else
        yum install -y php php-fpm php-xml php-cli \
                      php-mysqlnd php-pdo php-mbstring php-curl \
                      php-fileinfo php-gd php-zip php-opcache
        PHP_FPM_SERVICE="php-fpm"
    fi
    
    systemctl enable $PHP_FPM_SERVICE
    systemctl start $PHP_FPM_SERVICE
}

# 安装MySQL
install_mysql() {
    if [ "$SKIP_MYSQL_INSTALL" = true ]; then
        echo -e "${GREEN}跳过 MySQL 安装，使用现有服务${NC}"
        
        # 确保MySQL服务运行
        if systemctl is-active --quiet mysqld; then
            echo -e "${GREEN}MySQL 服务正在运行${NC}"
        else
            echo -e "${YELLOW}启动 MySQL 服务...${NC}"
            systemctl start mysqld
        fi
        return 0
    fi
    
    echo -e "${GREEN}=== 安装MySQL ===${NC}"
    
    # 清理可能存在的旧MySQL仓库
    echo -e "${YELLOW}清理旧MySQL仓库配置...${NC}"
    rpm -e mysql80-community-release --nodeps 2>/dev/null || true
    rm -f /etc/yum.repos.d/mysql-community*.repo
    
    # 安装MySQL仓库
    echo -e "${YELLOW}安装MySQL官方仓库...${NC}"
    
    # 方法1: 使用MySQL官方仓库
    wget -O /tmp/mysql80-community-release-el7-11.noarch.rpm https://dev.mysql.com/get/mysql80-community-release-el7-11.noarch.rpm
    if [ $? -eq 0 ]; then
        rpm -ivh /tmp/mysql80-community-release-el7-11.noarch.rpm
        # 更新yum缓存
        yum clean all
        yum makecache
    else
        echo -e "${YELLOW}MySQL官方仓库下载失败，尝试使用Remi仓库...${NC}"
        # 方法2: 使用Remi仓库的MySQL
        yum install -y mysql-server --enablerepo=remi
    fi
    
    # 安装MySQL服务器
    echo -e "${YELLOW}安装MySQL服务器...${NC}"
    if yum install -y mysql-community-server; then
        echo -e "${GREEN}MySQL 8.0 安装成功${NC}"
    else
        echo -e "${YELLOW}MySQL 8.0安装失败，尝试安装MariaDB...${NC}"
        # 方法3: 回退到MariaDB
        yum install -y mariadb-server mariadb
        if [ $? -eq 0 ]; then
            echo -e "${GREEN}MariaDB 安装成功${NC}"
            # 修改服务名称为mariadb
            MYSQL_SERVICE="mariadb"
        else
            echo -e "${RED}所有MySQL安装方法都失败了！${NC}"
            return 1
        fi
    fi
    
    # 启动MySQL服务
    echo -e "${YELLOW}启动MySQL服务...${NC}"
    systemctl enable mysqld
    systemctl start mysqld
    
    # 等待 MySQL 启动
    echo -e "${YELLOW}等待MySQL启动...${NC}"
    for i in {1..30}; do
        if systemctl is-active --quiet mysqld && [ -f /var/log/mysqld.log ]; then
            echo -e "${GREEN}MySQL启动成功${NC}"
            break
        fi
        echo -e "${YELLOW}等待MySQL启动...($i/30)${NC}"
        sleep 2
    done
    
    # 检查MySQL是否成功启动
    if ! systemctl is-active --quiet mysqld; then
        echo -e "${RED}MySQL启动失败，尝试查看日志...${NC}"
        journalctl -u mysqld --no-pager -n 20
        echo -e "${YELLOW}尝试重新初始化MySQL...${NC}"
        initialize_mysql
        return $?
    fi
    
    # 获取临时密码（仅适用于MySQL 8.0）
    if [ -f /var/log/mysqld.log ]; then
        TEMP_PASSWORD=$(grep 'temporary password' /var/log/mysqld.log | awk '{print $NF}' | tail -1)
        if [ -n "$TEMP_PASSWORD" ]; then
            echo -e "${YELLOW}MySQL临时密码: $TEMP_PASSWORD${NC}"
            
            # 尝试修改密码
            if mysql -u root -p"$TEMP_PASSWORD" --connect-expired-password -e "ALTER USER 'root'@'localhost' IDENTIFIED BY '$MYSQL_PASSWORD';" 2>/dev/null; then
                echo -e "${GREEN}MySQL root密码修改完成${NC}"
                mysql -u root -p"$MYSQL_PASSWORD" -e "FLUSH PRIVILEGES;" 2>/dev/null
            else
                echo -e "${YELLOW}标准密码修改失败，尝试安全模式...${NC}"
                secure_mysql_installation
            fi
        else
            echo -e "${YELLOW}未找到临时密码，尝试初始化MySQL...${NC}"
            secure_mysql_installation
        fi
    else
        # 没有日志文件的情况
        echo -e "${YELLOW}未找到MySQL日志文件，尝试安全安装...${NC}"
        secure_mysql_installation
    fi
}

# 初始化MySQL（用于启动失败的情况）
initialize_mysql() {
    echo -e "${YELLOW}正在初始化MySQL...${NC}"
    
    # 停止MySQL服务
    systemctl stop mysqld 2>/dev/null
    
    # 清理数据目录
    rm -rf /var/lib/mysql/*
    
    # 重新初始化MySQL
    mysqld --initialize --user=mysql
    
    # 重新设置权限
    chown -R mysql:mysql /var/lib/mysql
    
    # 启动MySQL服务
    systemctl start mysqld
    
    # 等待启动
    sleep 10
    
    if systemctl is-active --quiet mysqld; then
        echo -e "${GREEN}MySQL初始化成功${NC}"
        return 0
    else
        echo -e "${RED}MySQL初始化失败${NC}"
        return 1
    fi
}

# 安全的MySQL安装配置
secure_mysql_installation() {
    echo -e "${YELLOW}执行安全的MySQL安装配置...${NC}"
    
    # 停止MySQL服务
    systemctl stop mysqld
    
    # 设置MySQL免密码启动
    echo "[mysqld]" > /etc/my.cnf.d/skip-grant-tables.cnf
    echo "skip-grant-tables" >> /etc/my.cnf.d/skip-grant-tables.cnf
    
    # 启动MySQL服务
    systemctl start mysqld
    sleep 5
    
    # 检查MySQL是否运行
    if ! systemctl is-active --quiet mysqld; then
        echo -e "${RED}MySQL启动失败，无法进行安全配置${NC}"
        return 1
    fi
    
    # 重置root密码
    mysql -e "FLUSH PRIVILEGES;"
    mysql -e "ALTER USER 'root'@'localhost' IDENTIFIED BY '$MYSQL_PASSWORD';"
    mysql -e "FLUSH PRIVILEGES;"
    
    # 停止MySQL服务
    systemctl stop mysqld
    
    # 移除免密码配置
    rm -f /etc/my.cnf.d/skip-grant-tables.cnf
    
    # 重新启动MySQL服务
    systemctl start mysqld
    sleep 5
    
    # 验证密码设置
    if mysql -u root -p"$MYSQL_PASSWORD" -e "SELECT 1;" 2>/dev/null; then
        echo -e "${GREEN}MySQL root密码设置成功${NC}"
    else
        echo -e "${RED}MySQL密码设置失败，请手动配置${NC}"
        echo -e "${YELLOW}请运行: mysql_secure_installation${NC}"
        return 1
    fi
}

# 配置MySQL
configure_mysql() {
    echo -e "${GREEN}=== 配置MySQL ===${NC}"
    
    # 设置默认的MySQL服务名
    MYSQL_SERVICE="mysqld"
    
    # 等待MySQL服务完全启动
    sleep 5
    
    # 检查MySQL是否运行
    if ! systemctl is-active --quiet $MYSQL_SERVICE; then
        echo -e "${YELLOW}MySQL服务未运行，尝试启动...${NC}"
        systemctl start $MYSQL_SERVICE
        sleep 3
    fi

    # 检查MySQL连接
    if ! mysql -u root -p"$MYSQL_PASSWORD" -e "SELECT 1;" 2>/dev/null; then
        echo -e "${RED}无法连接MySQL，跳过数据库创建${NC}"
        echo -e "${YELLOW}请手动创建数据库后重新运行配置${NC}"
        return 1
    fi

    # 创建数据库函数
    create_database() {
        local db_name=$1
        local db_user=$2
        
        echo -e "${GREEN}=== 创建数据库 $db_name ===${NC}"
        
        # 多次尝试连接MySQL
        for i in {1..10}; do
            if mysql -u root -p"$MYSQL_PASSWORD" -e "SELECT 1" &>/dev/null; then
                echo -e "${GREEN}MySQL连接成功${NC}"
                break
            else
                echo -e "${YELLOW}第 $i 次尝试连接MySQL失败，等待重试...${NC}"
                sleep 3
            fi
        done

        # 最终尝试创建数据库
        if mysql -u root -p"$MYSQL_PASSWORD" -e "SELECT 1" &>/dev/null; then
            if mysql -u root -p"$MYSQL_PASSWORD" <<DB_SCRIPT
CREATE DATABASE IF NOT EXISTS $db_name DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER IF NOT EXISTS '$db_user'@'localhost' IDENTIFIED BY '$MYSQL_PASSWORD';
GRANT ALL PRIVILEGES ON $db_name.* TO '$db_user'@'localhost';
FLUSH PRIVILEGES;
DB_SCRIPT
            then
                echo -e "${GREEN}√ 数据库 $db_name 配置成功${NC}"
            else
                echo -e "${RED}× 数据库 $db_name 创建失败!${NC}"
                return 1
            fi
        else
            echo -e "${RED}× 无法连接MySQL，数据库 $db_name 创建失败!${NC}"
            echo -e "${YELLOW}请手动执行以下命令:${NC}"
            echo "1. 登录MySQL: mysql -u root -p"
            echo "2. 依次执行:"
            echo "   CREATE DATABASE IF NOT EXISTS $db_name DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
            echo "   CREATE USER IF NOT EXISTS '$db_user'@'localhost' IDENTIFIED BY '$MYSQL_PASSWORD';"
            echo "   GRANT ALL PRIVILEGES ON $db_name.* TO '$db_user'@'localhost';"
            echo "   FLUSH PRIVILEGES;"
            return 1
        fi
    }

    # 为每个系统创建数据库
    if $INSTALL_OA; then
        create_database "$OA_MYSQL_DB" "$OA_MYSQL_DB"
    fi

    if $INSTALL_BLOG; then
        create_database "$BLOG_MYSQL_DB" "$BLOG_MYSQL_DB"
    fi

    if $INSTALL_DEV; then
        create_database "$DEV_MYSQL_DB" "$DEV_MYSQL_DB"
    fi
}

# 安装Composer
install_composer_compatible() {
    echo -e "${GREEN}=== 安装Composer ===${NC}"
    
    # 检查PHP是否安装
    if ! command -v php >/dev/null 2>&1; then
        echo -e "${RED}PHP未安装，跳过Composer安装${NC}"
        return 1
    fi
    
    # 方法1: 使用官方安装脚本
    if curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer 2>/dev/null; then
        echo -e "${GREEN}Composer安装成功${NC}"
        return 0
    fi
    
    # 方法2: 直接下载
    if wget -O /usr/local/bin/composer https://getcomposer.org/composer-stable.phar 2>/dev/null; then
        chmod +x /usr/local/bin/composer
        echo -e "${GREEN}Composer安装成功（直接下载）${NC}"
        return 0
    fi
    
    echo -e "${YELLOW}Composer安装失败，跳过Composer安装${NC}"
    return 1
}

# 修改PHP上传大小
modify_php_upload_size() {
    echo -e "${GREEN}=== 修改PHP上传大小限制 ===${NC}"
    
    # 获取 PHP 配置
    if [ "$PHP_FPM_SERVICE" == "php83-php-fpm" ]; then
        PHP_INI_PATH="/etc/opt/remi/php83/php.ini"
    else
        PHP_INI_PATH="/etc/php.ini"
    fi

    # 检查 php.ini 文件是否存在
    if [ ! -f "$PHP_INI_PATH" ]; then
        echo -e "${YELLOW}未找到 $PHP_INI_PATH，跳过修改${NC}"
        return 1
    fi

    # 修改 upload_max_filesize 和 post_max_size
    echo "正在修改 $PHP_INI_PATH ..."
    sed -i 's/^;\?upload_max_filesize\s*=.*/upload_max_filesize = 100M/' "$PHP_INI_PATH"
    sed -i 's/^;\?post_max_size\s*=.*/post_max_size = 100M/' "$PHP_INI_PATH"

    # 重启 PHP-FPM
    if systemctl is-active --quiet "$PHP_FPM_SERVICE"; then
        echo "正在重启 $PHP_FPM_SERVICE ..."
        systemctl restart "$PHP_FPM_SERVICE"
        echo -e "${GREEN}PHP上传大小限制修改完成！${NC}"
    else
        echo -e "${YELLOW}PHP-FPM 未运行${NC}"
    fi
}

###########################################################
#                 用户输入配置部分                         #
###########################################################

# 选择要安装的系统
select_systems() {
    echo -e "${YELLOW}=== 请选择要安装的系统 (可多选) ===${NC}"
    echo "1. 勾股OA系统"
    echo "2. 勾股博客系统"
    echo "3. 勾股开发系统"
    read -p "请输入选择 (多个选择用空格分隔，默认全选): " SYSTEMS_CHOICE

    [ -z "$SYSTEMS_CHOICE" ] && SYSTEMS_CHOICE="1 2 3"
    IFS=' ' read -ra SYSTEMS <<< "$SYSTEMS_CHOICE"

    INSTALL_OA=false
    INSTALL_BLOG=false
    INSTALL_DEV=false

    for system in "${SYSTEMS[@]}"; do
        case $system in
            1) INSTALL_OA=true ;;
            2) INSTALL_BLOG=true ;;
            3) INSTALL_DEV=true ;;
        esac
    done
}

# 获取安装目录
get_install_dirs() {
    echo -e "${YELLOW}=== 请输入安装目录 ===${NC}"
    if $INSTALL_OA && ! $INSTALL_BLOG && ! $INSTALL_DEV; then
        read -p "勾股OA安装目录 (默认: /www/wwwroot/office): " OA_INSTALL_DIR
        OA_INSTALL_DIR=${OA_INSTALL_DIR:-/www/wwwroot/office}
    elif ! $INSTALL_OA && $INSTALL_BLOG && ! $INSTALL_DEV; then
        read -p "勾股博客安装目录 (默认: /www/wwwroot/blog): " BLOG_INSTALL_DIR
        BLOG_INSTALL_DIR=${BLOG_INSTALL_DIR:-/www/wwwroot/blog}
    elif ! $INSTALL_OA && ! $INSTALL_BLOG && $INSTALL_DEV; then
        read -p "勾股开发系统安装目录 (默认: /www/wwwroot/dev): " DEV_INSTALL_DIR
        DEV_INSTALL_DIR=${DEV_INSTALL_DIR:-/www/wwwroot/dev}
    else
        read -p "基础安装目录 (默认: /www/wwwroot): " BASE_INSTALL_DIR
        BASE_INSTALL_DIR=${BASE_INSTALL_DIR:-/www/wwwroot}
        
        $INSTALL_OA && OA_INSTALL_DIR="${BASE_INSTALL_DIR}/office"
        $INSTALL_BLOG && BLOG_INSTALL_DIR="${BASE_INSTALL_DIR}/blog"
        $INSTALL_DEV && DEV_INSTALL_DIR="${BASE_INSTALL_DIR}/dev"
    fi
}

# 获取MySQL配置信息
get_mysql_config() {
    echo -e "${YELLOW}=== 请输入MySQL配置信息 ===${NC}"
    
    # 如果使用现有MySQL，只需要密码
    if [ "$SKIP_MYSQL_INSTALL" = true ]; then
        echo -e "${GREEN}使用现有 MySQL 服务${NC}"
        if [ -z "$MYSQL_PASSWORD" ]; then
            read -s -p "请输入现有 MySQL root 密码: " MYSQL_PASSWORD
            echo
        fi
    else
        read -p "MySQL root用户 (默认: root): " MYSQL_USER
        MYSQL_USER=${MYSQL_USER:-root}

        while true; do
            read -s -p "MySQL root密码 (必须输入): " MYSQL_PASSWORD
            echo
            [ -z "$MYSQL_PASSWORD" ] && { echo -e "${RED}密码不能为空!${NC}"; continue; }
            
            read -s -p "再次输入MySQL root密码确认: " MYSQL_PASSWORD_CONFIRM
            echo
            
            [ "$MYSQL_PASSWORD" != "$MYSQL_PASSWORD_CONFIRM" ] && \
                echo -e "${RED}两次输入的密码不一致!${NC}" || break
        done

        read -p "MySQL主机地址 (默认: 127.0.0.1): " MYSQL_HOST
        MYSQL_HOST=${MYSQL_HOST:-127.0.0.1}

        read -p "MySQL端口 (默认: 3306): " MYSQL_PORT
        MYSQL_PORT=${MYSQL_PORT:-3306}
    fi

    # 为每个系统设置数据库名称
    if $INSTALL_OA; then
        read -p "勾股OA数据库名称 (默认: gouguoa): " OA_MYSQL_DB
        OA_MYSQL_DB=${OA_MYSQL_DB:-gouguoa}
    fi

    if $INSTALL_BLOG; then
        read -p "勾股博客数据库名称 (默认: gougublog): " BLOG_MYSQL_DB
        BLOG_MYSQL_DB=${BLOG_MYSQL_DB:-gougublog}
    fi

    if $INSTALL_DEV; then
        read -p "勾股开发系统数据库名称 (默认: gougudev): " DEV_MYSQL_DB
        DEV_MYSQL_DB=${DEV_MYSQL_DB:-gougudev}
    fi
}

# 获取Nginx端口配置
get_nginx_ports() {
    echo -e "${YELLOW}=== 请输入Nginx端口配置 ===${NC}"

    if $INSTALL_OA; then
        read -p "勾股OA HTTP端口 (默认: 6061): " OA_HTTP_PORT
        OA_HTTP_PORT=${OA_HTTP_PORT:-6061}
        
        read -p "勾股OA HTTPS端口 (默认: 6062): " OA_HTTPS_PORT
        OA_HTTPS_PORT=${OA_HTTPS_PORT:-6062}
    fi

    if $INSTALL_BLOG; then
        read -p "勾股博客 HTTP端口 (默认: 6071): " BLOG_HTTP_PORT
        BLOG_HTTP_PORT=${BLOG_HTTP_PORT:-6071}
        
        read -p "勾股博客 HTTPS端口 (默认: 6072): " BLOG_HTTPS_PORT
        BLOG_HTTPS_PORT=${BLOG_HTTPS_PORT:-6072}
    fi

    if $INSTALL_DEV; then
        read -p "勾股开发 HTTP端口 (默认: 6081): " DEV_HTTP_PORT
        DEV_HTTP_PORT=${DEV_HTTP_PORT:-6081}
        
        read -p "勾股开发 HTTPS端口 (默认: 6082): " DEV_HTTPS_PORT
        DEV_HTTPS_PORT=${DEV_HTTPS_PORT:-6082}
    fi
}

# 获取域名配置
get_domain_config() {
    read -p "域名 (留空则使用IP地址): " DOMAIN_NAME
    SERVER_NAME=${DOMAIN_NAME:-$(get_local_ip)}
}

# 安装勾股系统
install_gougu_systems() {
    echo -e "${GREEN}=== 下载并安装勾股系统 ===${NC}"

    # 安装Composer
    install_composer_compatible

    # 安装函数
    install_system() {
        local system_name=$1
        local git_url=$2
        local install_dir=$3
        
        echo -e "${GREEN}=== 安装 $system_name ===${NC}"
        mkdir -p "$(dirname "$install_dir")"

        # 备份已存在的目录
        if [ -d "$install_dir" ]; then
            BACKUP_DIR="${install_dir}.bak.$(date +%Y%m%d%H%M%S)"
            echo -e "${YELLOW}检测到已存在的安装目录，正在备份到 $BACKUP_DIR...${NC}"
            mv "$install_dir" "$BACKUP_DIR" || { echo -e "${YELLOW}备份失败，尝试删除旧目录...${NC}"; rm -rf "$install_dir"; }
        fi

        # 克隆代码
        git clone "$git_url" "$install_dir" || {
            echo -e "${RED}克隆 $system_name 仓库失败!${NC}"
            return 1
        }

        # 设置目录权限
        echo -e "${YELLOW}设置 $system_name 目录权限...${NC}"
        chmod -R 755 "$install_dir"
        
        # 设置关键目录的写权限
        chmod -R 777 "$install_dir"/app
        chmod -R 777 "$install_dir"/public
        chmod -R 777 "$install_dir"/config
        chmod -R 777 "$install_dir"/runtime
        
        # 设置上传目录权限（如果存在）
        if [ -d "$install_dir/public/uploads" ]; then
            chmod -R 777 "$install_dir/public/uploads"
        fi
        
        echo -e "${GREEN}✅ $system_name 目录权限设置完成${NC}"

        # 安装PHP依赖（如果composer可用）
        if command -v composer >/dev/null 2>&1; then
            echo -e "${GREEN}=== 安装 $system_name PHP依赖 ===${NC}"
            cd "$install_dir"
            composer install --ignore-platform-reqs --no-interaction || echo -e "${YELLOW}Composer安装过程中出现错误，尝试继续...${NC}"
        else
            echo -e "${YELLOW}Composer不可用，跳过PHP依赖安装${NC}"
        fi
    }

    # 安装各系统
    if $INSTALL_OA; then
        install_system "勾股OA" "https://gitee.com/gouguopen/office.git" "$OA_INSTALL_DIR"
        
        # 再次确认勾股OA权限
        echo -e "${YELLOW}确认勾股OA目录权限...${NC}"
        chmod -R 777 "$install_dir"/app
        chmod -R 777 "$OA_INSTALL_DIR"/public
        chmod -R 777 "$OA_INSTALL_DIR"/config
        chmod -R 777 "$OA_INSTALL_DIR"/runtime
        echo -e "${GREEN}✅ 勾股OA权限设置完成${NC}"
    fi

    if $INSTALL_BLOG; then
        install_system "勾股博客" "https://gitee.com/gouguopen/blog.git" "$BLOG_INSTALL_DIR"
        
        # 再次确认勾股博客权限
        echo -e "${YELLOW}确认勾股博客目录权限...${NC}"
        chmod -R 777 "$install_dir"/app
        chmod -R 777 "$BLOG_INSTALL_DIR"/public
        chmod -R 777 "$BLOG_INSTALL_DIR"/config
        chmod -R 777 "$BLOG_INSTALL_DIR"/runtime
        echo -e "${GREEN}✅ 勾股博客权限设置完成${NC}"
    fi

    if $INSTALL_DEV; then
        install_system "勾股开发系统" "https://gitee.com/gouguopen/dev.git" "$DEV_INSTALL_DIR"
        
        # 再次确认勾股开发系统权限
        echo -e "${YELLOW}确认勾股开发系统目录权限...${NC}"
        chmod -R 777 "$install_dir"/app
        chmod -R 777 "$DEV_INSTALL_DIR"/public
        chmod -R 777 "$DEV_INSTALL_DIR"/config
        chmod -R 777 "$DEV_INSTALL_DIR"/runtime
        echo -e "${GREEN}✅ 勾股开发系统权限设置完成${NC}"
    fi
}

# 配置Nginx
configure_nginx() {
    echo -e "${GREEN}=== 配置Nginx ===${NC}"

    NGINX_CONF_DIR="/etc/nginx/conf.d"

    # 生成SSL证书
    echo -e "${GREEN}=== 生成SSL证书 ===${NC}"
    mkdir -p /etc/nginx/ssl
    if [ -n "$DOMAIN_NAME" ]; then
        CN="$DOMAIN_NAME"
    else
        CN="localhost"
    fi

    openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
        -keyout /etc/nginx/ssl/cert.key \
        -out /etc/nginx/ssl/cert.crt \
        -subj "/C=CN/ST=Beijing/L=Beijing/O=YourCompany/OU=IT/CN=$CN" 2>/dev/null || {
        echo -e "${YELLOW}SSL证书生成失败，使用自签名证书${NC}"
    }

    # 设置SSL证书权限
    chmod 644 /etc/nginx/ssl/cert.crt
    chmod 644 /etc/nginx/ssl/cert.key
    chown nginx:nginx /etc/nginx/ssl/cert.crt
    chown nginx:nginx /etc/nginx/ssl/cert.key

    SSL_CERT_PATH="/etc/nginx/ssl/cert.crt"
    SSL_KEY_PATH="/etc/nginx/ssl/cert.key"

    # 检查 PHP-FPM 状态
    echo -e "${GREEN}=== 检查 PHP-FPM 服务状态 ===${NC}"
    if ! systemctl is-active --quiet "$PHP_FPM_SERVICE"; then
        echo -e "${YELLOW}PHP-FPM 服务未运行，尝试启动...${NC}"
        systemctl start "$PHP_FPM_SERVICE"
        sleep 3
    fi

    if systemctl is-active --quiet "$PHP_FPM_SERVICE"; then
        echo -e "${GREEN}PHP-FPM 服务运行正常${NC}"
        # 使用 TCP 连接
        PHP_FPM_SOCKET="127.0.0.1:9000"
    else
        echo -e "${RED}PHP-FPM 服务启动失败，使用 TCP 连接${NC}"
        PHP_FPM_SOCKET="127.0.0.1:9000"
    fi

    # 生成Nginx配置函数
    generate_nginx_config() {
        local system_name=$1
        local install_dir=$2
        local server_name=$3
        local http_port=$4
        local https_port=$5
        
        local conf_file="${NGINX_CONF_DIR}/${system_name}.conf"
        
        cat > "$conf_file" <<EOF
# HTTP配置
server {
    listen $http_port;
    listen [::]:$http_port;

    client_max_body_size 100M;
    root $install_dir/public;

    index index.html index.htm index.php;

    server_name $server_name;

    location / {
        if (!-e \$request_filename) {
            rewrite ^(.*)\$ /index.php?s=/\$1 last;
            break;
        }
    }

    location ~ \.php\$ {
        include fastcgi_params;
        fastcgi_pass $PHP_FPM_SOCKET;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
        fastcgi_read_timeout 300;
    }

    location /upload {
        client_max_body_size 100M;
    }

    location ~ /\.ht {
        deny all;
    }
}

# HTTPS配置
server {
    listen $https_port ssl;
    listen [::]:$https_port ssl;

    ssl_certificate ${SSL_CERT_PATH};
    ssl_certificate_key ${SSL_KEY_PATH};
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;

    client_max_body_size 100M;
    root $install_dir/public;

    index index.html index.htm index.php;

    server_name $server_name;

    location / {
        if (!-e \$request_filename) {
            rewrite ^(.*)\$ /index.php?s=/\$1 last;
            break;
        }
    }

    location ~ \.php\$ {
        include fastcgi_params;
        fastcgi_pass $PHP_FPM_SOCKET;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
        fastcgi_read_timeout 300;
    }

    location /upload {
        client_max_body_size 100M;
    }

    location ~ /\.ht {
        deny all;
    }
}
EOF
    }

    # 为每个系统生成Nginx配置
    if $INSTALL_OA; then
        generate_nginx_config "office" "$OA_INSTALL_DIR" "$SERVER_NAME" "$OA_HTTP_PORT" "$OA_HTTPS_PORT"
    fi

    if $INSTALL_BLOG; then
        generate_nginx_config "blog" "$BLOG_INSTALL_DIR" "$SERVER_NAME" "$BLOG_HTTP_PORT" "$BLOG_HTTPS_PORT"
    fi

    if $INSTALL_DEV; then
        generate_nginx_config "dev" "$DEV_INSTALL_DIR" "$SERVER_NAME" "$DEV_HTTP_PORT" "$DEV_HTTPS_PORT"
    fi

    # 测试Nginx配置并重启
    echo -e "${GREEN}测试Nginx配置...${NC}"
    if nginx -t; then
        echo -e "${GREEN}Nginx配置测试成功，重启Nginx...${NC}"
        systemctl restart nginx
        echo -e "${GREEN}Nginx重启完成${NC}"
    else
        echo -e "${RED}Nginx配置测试失败!${NC}"
        echo -e "${YELLOW}请检查Nginx配置: nginx -t${NC}"
    fi
}

# 配置防火墙
configure_firewall() {
    echo -e "${GREEN}=== 配置防火墙 ===${NC}"
    if command -v firewall-cmd &>/dev/null; then
        if $INSTALL_OA; then
            firewall-cmd --permanent --add-port=${OA_HTTP_PORT}/tcp
            firewall-cmd --permanent --add-port=${OA_HTTPS_PORT}/tcp
        fi
        if $INSTALL_BLOG; then
            firewall-cmd --permanent --add-port=${BLOG_HTTP_PORT}/tcp
            firewall-cmd --permanent --add-port=${BLOG_HTTPS_PORT}/tcp
        fi
        if $INSTALL_DEV; then
            firewall-cmd --permanent --add-port=${DEV_HTTP_PORT}/tcp
            firewall-cmd --permanent --add-port=${DEV_HTTPS_PORT}/tcp
        fi
        firewall-cmd --reload
        echo -e "${GREEN}防火墙配置完成${NC}"
    else
        echo -e "${YELLOW}未找到firewall-cmd，跳过防火墙配置${NC}"
    fi
}

# 保存系统配置信息
save_systems_config() {
    echo -e "${GREEN}=== 保存勾股系统配置信息 ===${NC}"
    cat > /etc/gougu_systems.conf << EOF
# 勾股系统配置信息
# 生成时间: $(date)

# 勾股OA系统配置
OA_INSTALL_DIR="$OA_INSTALL_DIR"
OA_MYSQL_DB="$OA_MYSQL_DB"
OA_HTTP_PORT="$OA_HTTP_PORT"
OA_HTTPS_PORT="$OA_HTTPS_PORT"

# 勾股博客系统配置
BLOG_INSTALL_DIR="$BLOG_INSTALL_DIR"
BLOG_MYSQL_DB="$BLOG_MYSQL_DB"
BLOG_HTTP_PORT="$BLOG_HTTP_PORT"
BLOG_HTTPS_PORT="$BLOG_HTTPS_PORT"

# 勾股开发系统配置
DEV_INSTALL_DIR="$DEV_INSTALL_DIR"
DEV_MYSQL_DB="$DEV_MYSQL_DB"
DEV_HTTP_PORT="$DEV_HTTP_PORT"
DEV_HTTPS_PORT="$DEV_HTTPS_PORT"

# MySQL配置
MYSQL_PASSWORD="$MYSQL_PASSWORD"
MYSQL_HOST="$MYSQL_HOST"
MYSQL_PORT="$MYSQL_PORT"

# 域名配置
DOMAIN_NAME="$DOMAIN_NAME"
SERVER_NAME="$SERVER_NAME"

# 服务配置
PHP_FPM_SERVICE="$PHP_FPM_SERVICE"
EOF
    chmod 600 /etc/gougu_systems.conf
    echo -e "${GREEN}配置信息已保存到 /etc/gougu_systems.conf${NC}"
}

# 显示安装完成信息
show_installation_complete() {
    echo -e "${GREEN}=== 勾股系统安装完成 ===${NC}"
    echo -e "以下是安装的系统及其访问地址:"

    if $INSTALL_OA; then
        echo -e "${YELLOW}=== 勾股OA系统 ===${NC}"
        echo -e "  HTTP: http://${SERVER_NAME}:${OA_HTTP_PORT}"
        echo -e "  HTTPS: https://${SERVER_NAME}:${OA_HTTPS_PORT}"
        echo -e "  数据库: ${OA_MYSQL_DB}"
        echo -e "  安装目录: ${OA_INSTALL_DIR}"
    fi

    if $INSTALL_BLOG; then
        echo -e "${YELLOW}=== 勾股博客系统 ===${NC}"
        echo -e "  HTTP: http://${SERVER_NAME}:${BLOG_HTTP_PORT}"
        echo -e "  HTTPS: https://${SERVER_NAME}:${BLOG_HTTPS_PORT}"
        echo -e "  数据库: ${BLOG_MYSQL_DB}"
        echo -e "  安装目录: ${BLOG_INSTALL_DIR}"
    fi

    if $INSTALL_DEV; then
        echo -e "${YELLOW}=== 勾股开发系统 ===${NC}"
        echo -e "  HTTP: http://${SERVER_NAME}:${DEV_HTTP_PORT}"
        echo -e "  HTTPS: https://${SERVER_NAME}:${DEV_HTTPS_PORT}"
        echo -e "  数据库: ${DEV_MYSQL_DB}"
        echo -e "  安装目录: ${DEV_INSTALL_DIR}"
    fi

    echo -e "\n${GREEN}服务状态:${NC}"
    echo -e "Nginx状态: $(systemctl is-active nginx)"
    echo -e "MySQL状态: $(systemctl is-active mysqld)"
    echo -e "PHP-FPM状态: $(systemctl is-active $PHP_FPM_SERVICE)"

    echo -e "\n${YELLOW}安装完成！请通过上述地址访问系统。${NC}"
}

# 卸载勾股系统
uninstall_gougu_systems() {
    echo -e "${GREEN}=== 开始卸载勾股系统 ===${NC}"
    
    # 读取配置文件（如果存在）
    if [ -f "/etc/gougu_systems.conf" ]; then
        source "/etc/gougu_systems.conf"
        echo -e "${YELLOW}从配置文件读取安装信息...${NC}"
    else
        echo -e "${YELLOW}未找到配置文件，使用默认值...${NC}"
    fi
    
    # 选择要卸载的系统
    echo -e "${YELLOW}=== 请选择要卸载的系统 (可多选) ===${NC}"
    echo "1. 勾股OA系统"
    echo "2. 勾股博客系统"
    echo "3. 勾股开发系统"
    read -p "请输入选择 (多个选择用空格分隔，默认全选): " UNINSTALL_CHOICE

    [ -z "$UNINSTALL_CHOICE" ] && UNINSTALL_CHOICE="1 2 3"
    IFS=' ' read -ra UNINSTALL_SYSTEMS <<< "$UNINSTALL_CHOICE"

    UNINSTALL_OA=false
    UNINSTALL_BLOG=false
    UNINSTALL_DEV=false

    for system in "${UNINSTALL_SYSTEMS[@]}"; do
        case $system in
            1) UNINSTALL_OA=true ;;
            2) UNINSTALL_BLOG=true ;;
            3) UNINSTALL_DEV=true ;;
        esac
    done

    # 如果没有配置文件，询问必要信息
    if [ ! -f "/etc/gougu_systems.conf" ]; then
        if $UNINSTALL_OA; then
            read -p "请输入勾股OA安装目录 (默认: /www/wwwroot/office): " OA_INSTALL_DIR
            OA_INSTALL_DIR=${OA_INSTALL_DIR:-/www/wwwroot/office}
            read -p "请输入勾股OA数据库名称 (默认: gouguoa): " OA_MYSQL_DB
            OA_MYSQL_DB=${OA_MYSQL_DB:-gouguoa}
        fi
        
        if $UNINSTALL_BLOG; then
            read -p "请输入勾股博客安装目录 (默认: /www/wwwroot/blog): " BLOG_INSTALL_DIR
            BLOG_INSTALL_DIR=${BLOG_INSTALL_DIR:-/www/wwwroot/blog}
            read -p "请输入勾股博客数据库名称 (默认: gougublog): " BLOG_MYSQL_DB
            BLOG_MYSQL_DB=${BLOG_MYSQL_DB:-gougublog}
        fi
        
        if $UNINSTALL_DEV; then
            read -p "请输入勾股开发系统安装目录 (默认: /www/wwwroot/dev): " DEV_INSTALL_DIR
            DEV_INSTALL_DIR=${DEV_INSTALL_DIR:-/www/wwwroot/dev}
            read -p "请输入勾股开发系统数据库名称 (默认: gougudev): " DEV_MYSQL_DB
            DEV_MYSQL_DB=${DEV_MYSQL_DB:-gougudev}
        fi
        
        read -p "请输入MySQL root密码: " MYSQL_PASSWORD
    fi

    # 显示卸载确认信息
    echo -e "${RED}警告：此操作将永久删除以下内容：${NC}"
    if $UNINSTALL_OA; then
        echo -e "  - 勾股OA安装目录: $OA_INSTALL_DIR"
        echo -e "  - 勾股OA数据库: $OA_MYSQL_DB"
        echo -e "  - Nginx配置文件: /etc/nginx/conf.d/office.conf"
    fi
    if $UNINSTALL_BLOG; then
        echo -e "  - 勾股博客安装目录: $BLOG_INSTALL_DIR"
        echo -e "  - 勾股博客数据库: $BLOG_MYSQL_DB"
        echo -e "  - Nginx配置文件: /etc/nginx/conf.d/blog.conf"
    fi
    if $UNINSTALL_DEV; then
        echo -e "  - 勾股开发系统安装目录: $DEV_INSTALL_DIR"
        echo -e "  - 勾股开发系统数据库: $DEV_MYSQL_DB"
        echo -e "  - Nginx配置文件: /etc/nginx/conf.d/dev.conf"
    fi
    
    read -p "确定要卸载选中的勾股系统吗？此操作不可逆！(y/N): " CONFIRM_UNINSTALL
    
    if [[ ! $CONFIRM_UNINSTALL =~ ^[Yy]$ ]]; then
        echo -e "${YELLOW}卸载操作已取消${NC}"
        return 1
    fi

    # 卸载函数
    uninstall_system() {
        local system_name=$1
        local install_dir=$2
        local db_name=$3
        local nginx_conf="$4"
        
        echo -e "${YELLOW}=== 卸载 $system_name ===${NC}"
        
        # 删除安装目录
        if [ -d "$install_dir" ]; then
            echo -e "${YELLOW}删除安装目录: $install_dir${NC}"
            rm -rf "$install_dir"
            echo -e "${GREEN}安装目录已删除${NC}"
        else
            echo -e "${YELLOW}安装目录不存在: $install_dir${NC}"
        fi
        
        # 删除Nginx配置文件
        if [ -f "$nginx_conf" ]; then
            echo -e "${YELLOW}删除Nginx配置文件: $nginx_conf${NC}"
            rm -f "$nginx_conf"
            echo -e "${GREEN}Nginx配置文件已删除${NC}"
        fi
        
        # 删除数据库
        if [ -n "$MYSQL_PASSWORD" ] && [ -n "$db_name" ]; then
            echo -e "${YELLOW}删除数据库: $db_name${NC}"
            if mysql -u root -p"$MYSQL_PASSWORD" -e "DROP DATABASE IF EXISTS $db_name;" 2>/dev/null; then
                echo -e "${GREEN}数据库 $db_name 已删除${NC}"
            else
                echo -e "${RED}删除数据库失败，可能需要手动删除${NC}"
            fi
        fi
    }

    # 执行卸载
    if $UNINSTALL_OA; then
        uninstall_system "勾股OA系统" "$OA_INSTALL_DIR" "$OA_MYSQL_DB" "/etc/nginx/conf.d/office.conf"
    fi

    if $UNINSTALL_BLOG; then
        uninstall_system "勾股博客系统" "$BLOG_INSTALL_DIR" "$BLOG_MYSQL_DB" "/etc/nginx/conf.d/blog.conf"
    fi

    if $UNINSTALL_DEV; then
        uninstall_system "勾股开发系统" "$DEV_INSTALL_DIR" "$DEV_MYSQL_DB" "/etc/nginx/conf.d/dev.conf"
    fi

    # 重新加载Nginx配置
    echo -e "${YELLOW}重新加载Nginx配置...${NC}"
    if nginx -t 2>/dev/null; then
        systemctl reload nginx 2>/dev/null && echo -e "${GREEN}Nginx配置已重新加载${NC}" || echo -e "${YELLOW}Nginx重新加载失败${NC}"
    fi

    echo -e "${GREEN}=== 勾股系统卸载完成 ===${NC}"
}

# 主安装流程
perform_installation() {
    echo -e "${GREEN}=== 开始安装基础软件 ===${NC}"
    install_base_software

    echo -e "${GREEN}=== 关闭 SELinux ===${NC}"
    disable_selinux

    echo -e "${GREEN}=== 开始安装Nginx ===${NC}"
    install_nginx

    echo -e "${GREEN}=== 开始安装PHP ===${NC}"
    install_php

    echo -e "${GREEN}=== 开始安装MySQL ===${NC}"
    install_mysql

    # 修改PHP上传大小
    modify_php_upload_size

    # 配置MySQL
    configure_mysql

    # 安装勾股系统
    install_gougu_systems

    # 配置Nginx
    configure_nginx

    # 配置防火墙
    configure_firewall

    # 保存配置信息
    save_systems_config

    # 显示安装完成信息
    show_installation_complete
}

###########################################################
#                      主程序逻辑                         #
###########################################################

# 主程序入口
main() {
    # 首先检查系统兼容性
    check_system_compatibility
    
    # 配置镜像源
    configure_centos_repo
    
    # 询问用户是否升级系统（必须升级才能继续）
    ask_system_upgrade
    
    # 检测已存在的服务
    detect_existing_services
    
    # 处理已存在的服务
    handle_existing_services
    
    case "$1" in
        "uninstall")
            uninstall_gougu_systems
            ;;
        "install")
            show_welcome
            select_systems
            get_install_dirs
            get_mysql_config
            get_nginx_ports
            get_domain_config
            perform_installation
            ;;
        *)
            show_main_menu
            case $MAIN_CHOICE in
                1)
                    show_welcome
                    select_systems
                    get_install_dirs
                    get_mysql_config
                    get_nginx_ports
                    get_domain_config
                    perform_installation
                    ;;
                2)
                    uninstall_gougu_systems
                    ;;
                3)
                    echo -e "${GREEN}退出脚本${NC}"
                    exit 0
                    ;;
                *)
                    echo -e "${RED}无效选择，退出脚本${NC}"
                    exit 1
                    ;;
            esac
            ;;
    esac
}

# 如果提供了参数，直接执行相应功能
if [ $# -gt 0 ]; then
    case "$1" in
        "install")
            main "install"
            ;;
        "uninstall")
            main "uninstall"
            ;;
        *)
            echo "用法: $0 [install|uninstall]"
            echo "   install   - 安装勾股系统"
            echo "   uninstall - 卸载勾股系统"
            exit 1
            ;;
    esac
else
    # 没有参数时显示主菜单
    main
fi